﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace hmi
{    
    class Utility
    {        
        public static string BytesToHexString(byte[] bytes)     //将字节流的数据转为以16进制表示的字符串，比如byte data = 0x34，将之转化成字符串"34"
        {
            string resultStr = string.Empty;
            int length = bytes.Length;
            for (int i = 0; i < length; i++)//逐字节变为16进制字符
            {
                //int j = i + 1;
                //string receiveStr = string.Format("收到数据中第{0:G}字节为0X{1:X}", j, bytes[i]);                
                string strTemp = Convert.ToString(bytes[i], 16).ToUpper().PadLeft(2, '0');
                resultStr += strTemp + " ";

            }
            return resultStr;
        }

        //public static string HexStringToString(string hexStr, Encoding encode = null)  //将字节流的数据转为字符串（字符串就有个编码问题，比如UTF8），比如byte data = 0x34,将之转化为字符串"4"，与BytesToHexString这个函数区别是，对于同样的字节数据，解码方式不一样
        //{
        //    hexStr = hexStr.Replace(" ", "");
        //    encode = encode ?? Encoding.UTF8;
        //    int length = hexStr.Length / 2;
        //    byte[] resultBytes = new byte[length];
        //    for (int i = 0; i < length; i++)
        //    {
        //        string str = hexStr.Substring(i * 2, 2);
        //        resultBytes[i] = Convert.ToByte(str, 16);
        //    }
        //    //按照指定编码将字节数组变为字符串
        //    return encode.GetString(resultBytes);
        //}

        public static byte[] HexStringToBytes(string hexStr)  //将16进制表示的字符串转为字节流，比如字符串为"34F6",转为byte数组 byte[0]为34，byte[1]为F6
        {            
            hexStr = hexStr.Replace(" ", "");//去除16进制数据中所有空格
            hexStr = hexStr.Replace("\r", "");//去除16进制数据中所有换行
            hexStr = hexStr.Replace("\n", "");//去除16进制数据中所有换行
            int hexStrLen = hexStr.Length;
            if (hexStrLen % 2 != 0)
            {
                hexStr = hexStr.Substring(0, hexStrLen - 1)+ (hexStr[hexStrLen - 1]+"").PadLeft(2, '0');
            }                     
            int byteLen = hexStr.Length / 2;            
            byte[] resultBytes = new byte[byteLen];
            for (int i = 0; i < byteLen; i++)
            {
                string str = hexStr.Substring(i * 2, 2);
                try
                {
                    resultBytes[i] = Convert.ToByte(str, 16);
                }
                catch
                {
                    return null;
                }
            }
            //按照指定编码将字节数组变为字符串
            return resultBytes;
        }
    }
}
